package com.singfan.common.util;

import com.singfan.common.SingFanException;

import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 压缩工具
 * Author: HanSongHe
 * Date: 2015-07-27 14:06
 * Desc:
 */
public class CompressUtil {
    /**
     * 使用标准的zip压缩算法压缩数据（data长度大于0时才真正压缩，否则原样返回）
     * @param data 要压缩的数据
     * @return 压缩后的数据
     */
    public static byte[] zip(byte[] data) {
        byte[] result;
        if(data != null && data.length > 0){
            Deflater deflater = new Deflater(9, true);
            deflater.reset();
            deflater.setInput(data);
            deflater.finish();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(data.length);

            try {
                byte[] buf = new byte[1024];
                while (!deflater.finished()) {
                    int i = deflater.deflate(buf);
                    byteArrayOutputStream.write(buf, 0, i);
                }
                byteArrayOutputStream.flush();
                result = byteArrayOutputStream.toByteArray();
                byteArrayOutputStream.close();
            }
            catch (Exception ex){
                throw new SingFanException(String.format("CompressUtil.zip() error: %s !", ex.getMessage()), ex);
            }
            finally {
                deflater.end();
            }
        }
        else{
            result = data;
        }

        return result;
    }

    /**
     * 使用标准的zip压缩算法解压数据（data长度大于0时才真正解压，否则原样返回）
     * @param data 要解压的数据
     * @return 解压后的数据
     */
    public static byte[] unzip(byte[] data) {
        byte[] result;
        if (data != null && data.length > 0) {
            Inflater inflater = new Inflater(true);
            inflater.reset();
            inflater.setInput(data);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(data.length);
            try {
                byte[] buf = new byte[1024];
                while (!inflater.finished()) {
                    int i = inflater.inflate(buf);
                    byteArrayOutputStream.write(buf, 0, i);
                }
                byteArrayOutputStream.flush();
                result = byteArrayOutputStream.toByteArray();
                byteArrayOutputStream.close();
            }
            catch (Exception ex) {
                throw new SingFanException(String.format("CompressUtil.unzip() error: %s !", ex.getMessage()), ex);
            }
            finally {
                inflater.end();
            }
        } else {
            result = data;
        }

        return result;
    }
}
